<?php

namespace mpend\modules\user\models;

use Yii;
use mpend\models\User;
use common\models\member\Member;

class MemberForm extends \common\base\Model {

    /**
     * @var string 
     */
    public $user_id;

    /**
     * @var string 姓名
     */
    public $name;

    /**
     * @var string 会员号
     */
    public $lntsno;

    /**
     * @var string 年票号
     */
    public $year;

    /**
     * @var string 注册类型
     */
    public $type = 0;

    /**
     * @var User|null 用户信息
     */
    private $_user;

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['user_id', 'type'], 'integer'],
            [['user_id', 'name', 'lntsno', 'year'], 'required'],
            [['name'], 'string', 'max' => 8],
            [['year', 'lntsno'], 'string'],
            [['user_id'], 'validateUser'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'name' => '姓名',
            'lntsno' => '证件号码',
            'year' => '年票号',
            'type' => '认证类型',
        ];
    }

    /**
     * 校验唯一手机号
     */
    public function validateUser($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        $userClass = Yii::$app->user->identityClass;
        $user = $userClass::findIdentity($this->$attribute);
        if (!$user) {
            return $this->addError($attribute, '请登录后完善个人资料信息');
        }
        $this->_user = $user;
    }

    /**
     * @return User
     */
    public function getUser() {
        return $this->_user;
    }

    /**
     * 保存动态信息（发布&修改）
     * @param [type] $data
     * @return void
     */
    public function save() {
        if (!$this->validate()) {
            return $this->dumpError('');
        }
        $user = $this->getUser();
        /* @var $model \common\models\user\Member */
        $model = Member::findOrNew([
            'user_id' => $user->id
        ]);
        $model->setAttributes([
            'realname' => $this->name,
            'lntsno' => $this->lntsno,
            'ticketno' => $this->year,
            'type' => $this->type,
        ]);
        //开启事务
        $transaction = Yii::$app->db->beginTransaction();
        try {
            if (!$model->save()) {
                return $this->dumpError('认证信息保存失败');
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            $this->dumpError($e->getMessage());
        }
        return $model;
    }

}
